<template>
  <BasicModal @register="modalRegister" :okText="SAVE" @ok="onSave" @cancel="onFinish">
    <Tree
      :treeData="permissionTree"
      :replaceFields="{
        children: 'children',
        title: 'title',
        key: 'id',
      }"
      checkable
      checkStrictly
      v-model:checkedKeys="rolePermission"
      @check="onCheck"
    >
      <template #title="{ title }">
        {{ title }}
      </template>
    </Tree>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { Tree } from 'ant-design-vue';
  import { SAVE } from '/@/constant';

  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { RoleListModel } from '../model';
  import { getPermissionTree } from '/@/api/system/permission';
  import { SimplePermissionModel } from '/@/api/system/model/permission';
  import { authorize, getPermission } from '../api';
  import { checked, TreeChecked } from '/@/utils/treeUtil';

  const id = ref<string>('');
  const permissionTree = ref<SimplePermissionModel[]>([]);
  const rolePermission = ref<TreeChecked>({
    checked: [],
    halfChecked: [],
  });

  const [modalRegister, { setModalProps, closeModal, changeLoading, changeOkLoading }] =
    useModalInner(async (data: RoleListModel) => {
      changeLoading(true);
      changeOkLoading(true);
      permissionTree.value = await getPermissionTree();
      const { name } = data;
      id.value = data.id;
      const result = await getPermission({ id: data.id });

      rolePermission.value = checked(permissionTree.value, result, { id: 1, checked: false });
      setModalProps({ title: `为角色《${name}》授权` });
      changeLoading(false);
      changeOkLoading(false);
    });

  const onSave = () => {
    const { checked, halfChecked } = unref(rolePermission);
    const permissions = [...checked, ...halfChecked];
    authorize({ id: unref(id), permissions });
    onFinish();
  };

  const onCheck = (checkedKeys, e) => {
    const { checked: checkedList } = checkedKeys;
    const { node } = e;
    const bool: boolean = e.checked;
    const { eventKey } = unref(node);
    rolePermission.value = checked(permissionTree.value, checkedList, {
      checked: bool,
      id: eventKey,
    });
  };

  const onFinish = () => {
    closeModal();
    permissionTree.value = [];
    rolePermission.value = {
      checked: [],
      halfChecked: [],
    };
  };
</script>

<style scoped></style>
